import axios from 'axios';
import store from '@/store';

const service = axios.create({
  baseURL: 'https://bar.009bar.com',
  timeout: 15000,
});

service.interceptors.request.use((config) => {
  const { token } = store.state;
  if (token) {
    if (config.method && config.method.toLowerCase() === 'get') {
      config.params = {
        ...(config.params || {}),
        token,
      };
    } else if (config.data && typeof config.data === 'object') {
      config.data = {
        ...config.data,
        token,
      };
    } else {
      config.headers.token = token;
    }
  }
  return config;
});

service.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data && Number(data.code) === 200) {
      return data.data;
    }
    const message = (data && (data.msg || data.message)) || '点数风暴接口请求失败';
    return Promise.reject(new Error(message));
  },
  (error) => Promise.reject(error),
);

export default service;
